#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
基于事件系统的插件基类
"""

from abc import ABC, abstractmethod
from typing import Dict, Optional, Any
import asyncio
from common.logger import logger
from plugins.event_system import EventBus, Event, EventType, on_message, on_any_message


class BasePlugin(ABC):
    """基于事件系统的插件基类"""
    
    def __init__(self, config: Dict[str, Any], event_bus: EventBus):
        self.config = config
        self.name = config.get("name", "未知插件")
        self.version = config.get("version", "1.0.0")
        self.description = config.get("description", "")
        self.author = config.get("author", "")
        self.enabled = config.get("enabled", True)
        self.settings = config.get("settings", {})
        self.event_bus = event_bus
        
        # 注册事件监听器
        self._register_event_handlers()
        
        logger.info(f"插件 {self.name} v{self.version} 已初始化")
    
    def _register_event_handlers(self):
        """注册事件处理器"""
        # 查找所有使用装饰器的方法
        for attr_name in dir(self):
            attr = getattr(self, attr_name)
            if hasattr(attr, '_is_event_handler') and attr._is_event_handler:
                # 这是一个事件处理器
                event_type = attr._event_type
                self.event_bus.add_listener(event_type, attr, asyncio.iscoroutinefunction(attr))
                logger.debug(f"注册事件处理器: {self.name}.{attr_name} -> {event_type.name}")
            
            elif hasattr(attr, '_is_middleware') and attr._is_middleware:
                # 这是一个中间件
                self.event_bus.add_middleware(attr)
                logger.debug(f"注册中间件: {self.name}.{attr_name}")
    
    def get_setting(self, key: str, default=None):
        """获取插件设置"""
        return self.settings.get(key, default)
    
    def set_setting(self, key: str, value: Any):
        """设置插件设置"""
        self.settings[key] = value
    
    def is_enabled(self) -> bool:
        """检查插件是否启用"""
        return self.enabled
    
    def enable(self):
        """启用插件"""
        self.enabled = True
        logger.info(f"插件 {self.name} 已启用")
    
    def disable(self):
        """禁用插件"""
        self.enabled = False
        logger.info(f"插件 {self.name} 已禁用")
    
    def get_info(self) -> Dict[str, Any]:
        """获取插件信息"""
        return {
            "name": self.name,
            "version": self.version,
            "description": self.description,
            "author": self.author,
            "enabled": self.enabled,
            "settings": self.settings
        }
    
    async def on_load(self):
        """插件加载时调用"""
        logger.info(f"插件 {self.name} 加载完成")
    
    async def on_unload(self):
        """插件卸载时调用"""
        logger.info(f"插件 {self.name} 卸载完成")
    
    def create_text_response(self, content: str) -> Dict[str, Any]:
        """创建文本响应"""
        return {
            "type": "text",
            "content": content
        }
    
    def create_image_response(self, image_url: str) -> Dict[str, Any]:
        """创建图片响应"""
        return {
            "type": "image",
            "content": image_url
        }
    
    def create_file_response(self, file_url: str) -> Dict[str, Any]:
        """创建文件响应"""
        return {
            "type": "file",
            "content": file_url
        }
    
    def handle_event(self, event: Event) -> Optional[Dict[str, Any]]:
        """处理事件的抽象方法"""
        pass


@on_message(EventType.MESSAGE_TEXT)
async def handle_text_message(msg_type: int, sender_wxid: str, from_wxid: str, 
                           content: str, is_group: bool, msg_api: Any):
    # 实现文本消息处理逻辑
    pass


@on_message(EventType.MESSAGE_IMAGE)
async def handle_image_message(msg_type: int, sender_wxid: str, from_wxid: str, 
                           content: str, is_group: bool, msg_api: Any):
    # 实现图片消息处理逻辑
    pass


@on_message(EventType.MESSAGE_MULTIMEDIA)
async def handle_file_message(msg_type: int, sender_wxid: str, from_wxid: str, 
                           content: str, is_group: bool, msg_api: Any):
    # 实现文件消息处理逻辑
    pass


@on_any_message()
async def handle_any_message(msg_type: int, sender_wxid: str, from_wxid: str, 
                           content: str, is_group: bool, msg_api: Any):
    # 实现任何消息处理逻辑
    pass 